package com.core.util;

import com.core.comment.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.MDC;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
public class CommonUtil {

    public static long getCurrSec() {
        return System.currentTimeMillis() / 1000;
    }

    public static long ms2Sec(long timeStamp) {
        if (timeStamp > 10000000000l) {
            return TimeUnit.MILLISECONDS.toSeconds(timeStamp);
        }
        return timeStamp;
    }

    public static String toString(Object obj) {
        return obj == null ? "" : String.valueOf(obj);
    }

    public static Long toLong(Object obj) {
        try {
            return obj != null ? Long.valueOf(toString(obj)) : 0;
        } catch (Exception e) {
            return 0l;
        }
    }


    public static Integer toInt(Object obj) {
        try {
            return obj != null ? Integer.valueOf(toString(obj)) : 0;
        } catch (Exception e) {
            return 0;
        }
    }

    public static long toShortTime(long time) {
        if (time >= 10000000000L) {
            time = time / 1000;
        }
        return time;
    }

    public static long getLongTraceId() {
        long traceid = (long) (System.currentTimeMillis() * 1e6 + Math.random() * 1e6);
        return traceid;
    }

    public static String getTraceId() {
        long traceid = (long) (System.currentTimeMillis() * 1e6 + Math.random() * 1e6);
        return String.valueOf(traceid);
    }

    public static void setTraceIdMdc() {
        MDC.put("traceId", getTraceId());
    }

    public static String getTraceIdMdc() {
        return getMDCValue("traceId");
    }

    public static String getCmd() {
        String cmd = MDC.get("cmd");
        return StringUtil.isEmpty(cmd) ? "" : cmd;
    }

    public static void setMDCValue(String key, String value) {
        MDC.put(key, value);
    }

    public static String getMDCValue(String key) {
        try {
            String value = MDC.get(key);
            return StringUtil.isEmpty(value) ? "" : value;
        } catch (Exception e) {
            log.error("MD5 get error:", e);
            return "";
        }
    }

    public static String getTimeByFormat(long date, String format) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        String result = dateFormat.format(Calendar.getInstance().getTimeInMillis());
        return result;
    }

    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);

            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * excel 导出.
     *
     * @param dataList 导出数据
     * @param fileName 文件名
     * @param path     二级路径
     * @return 路径
     */
    public static String toSheet(List<List<String>> dataList, String fileName, String path) {
        String url = "/report/" + path + "/";
        HSSFWorkbook wb = null;
        try {
            File desFile = new File(path);
            if (!desFile.exists()) {
                // 目录不存在的情况下，创建目录。
                desFile.mkdirs();
            }
            FileOutputStream output = new FileOutputStream(
                    path + "/" + fileName + ".xls");
            // 创建HSSFWorkbook对象
            wb = new HSSFWorkbook();

            // 创建HSSFSheet对象
            HSSFSheet sheet = wb.createSheet(fileName);
            // 创建HSSFRow对象
            HSSFRow row;
            for (int j = 0; j < dataList.size(); j++) {
                row = sheet.createRow(j);
                List<String> strings = dataList.get(j);
                for (int i = 0; i < strings.size(); i++) {
                    row.createCell(i).setCellValue(strings.get(i));
                }
            }
            // 输出Excel文件
            output.flush();
            wb.write(output);
            url += fileName + ".xls";
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return url;
    }

}
